
import { ElMessage } from "element-plus";
import { defineStore } from "pinia";
import { ref, computed } from "vue";

export const useUserStore = defineStore("user", () => {
  // 状态
  const userInfo = ref(null);
  const token = ref("");
  const isLoggedIn = ref(false);

  const userId = computed(() => {
    return userInfo.value?.userId || -1;
  });

  const username = computed(() => {
    return userInfo.value?.username || "";
  });

  const userType = computed(() => {
    return userInfo.value?.userType || 0;
  });

  const avatarPath = computed(() => {
    return userInfo.value?.avatarPath || "";
  });

  // 操作方法
  const setUserInfo = (info) => {
    userInfo.value = info.record;
    token.value = info.token;
    isLoggedIn.value = true;
    // 同时保存到localStorage
    localStorage.setItem(
      "hudazx_vue_blogStorage",
      JSON.stringify({ record: info })
    );
  };

  const login = (loginData) => {
    setUserInfo(loginData);
  };

  const logout = () => {
    userInfo.value = null;
    isLoggedIn.value = false;
    token.value = "";
    localStorage.removeItem("hudazx_vue_blogStorage");
  };

  const initUserFromStorage = () => {
    try {
      const storageData = localStorage.getItem("hudazx_vue_blogStorage");
      // console.log(storageData);
      if (storageData) {
        const parsedData = JSON.parse(storageData);
        if (parsedData && parsedData.record) {
          userInfo.value = parsedData.record;
          isLoggedIn.value = true;
        }
      }
    } catch (error) {
      console.error("初始化用户信息失败:", error);
      localStorage.removeItem("hudazx_vue_blogStorage");
    }
  };

  const updateUserInfo = (updates) => {
    if (userInfo.value) {
      userInfo.value = { ...userInfo.value, ...updates };
      // 更新localStorage
      localStorage.setItem(
        "hudazx_vue_blogStorage",
        JSON.stringify({ record: userInfo.value })
      );
    }
  };

  return {
    // 状态
    userInfo,
    isLoggedIn,
    // 计算属性
    username,
    userType,
    userId,
    avatarPath,
    // 方法
    setUserInfo,
    login,
    logout,
    initUserFromStorage,
    updateUserInfo,
  };
});
